﻿
using System;

using UnityEngine;

/// <summary>
/// Tween a value. This is not actually a Tweener, it's like a convenient linear value provider.
/// </summary>
[AddComponentMenu("UGUI/Tween/Tween Value")]
public class UGUITweenValue : UGUITweener
{
    public Action<UGUITweenValue, float> onUpdate;

    public override object fromValue { get { return from; } set { from = (float)value; } }
    public override object toValue { get { return to; } set { to = (float)value; } }
    public object Args { get { return args; } set { args = value; } }

    public float from = 0.0f;
	public float to = 1.0f;
    public object args;

    private float _value;

    /// <summary>
    /// Tween's current value.
    /// </summary>
    public float value
    {
        get
        {
            return _value;
        }
        set
        {
            _value = value;
        }
    }

    /// <summary>
    /// Tween the value.
    /// </summary>
    protected override void OnUpdate (float factor, bool isFinished)
	{
        _value = from * (1f - factor) + to * factor;

        if (onUpdate != null)
        {
            onUpdate(this, _value);
        }
	}

    /// <summary>
    /// Start the tweening operation.
    /// </summary>
    static public UGUITweenValue Begin(GameObject go, float duration, float fromValue, float toValue, object args, Action<UGUITweenValue, float> onUpdate)
    {
        UGUITweenValue comp = UGUITweener.Begin<UGUITweenValue>(go, duration);
        comp.from = fromValue;
        comp.to = toValue;
        comp.onUpdate += onUpdate;

        if (duration <= 0f)
        {
            comp.Sample(1f, true);
            comp.enabled = false;

            if (comp.onUpdate != null) { comp.onUpdate(comp, 1.0f); }
        }

        return comp;
    }

	[ContextMenu("Set 'From' to current value")]
	public override void SetStartToCurrentValue () { from = value; }

	[ContextMenu("Set 'To' to current value")]
	public override void SetEndToCurrentValue () { to = value; }

	[ContextMenu("Assume value of 'From'")]
	void SetCurrentValueToStart () { value = from; }

	[ContextMenu("Assume value of 'To'")]
	void SetCurrentValueToEnd () { value = to; }
}
